package com.addressBook.tools;

import com.addressBook.bean.Groups;
import com.addressBook.bean.UserInfo;
import com.addressBook.util.AllUtil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 主要分析vcf文件
 *
 * @author Lam
 */
public class Parser {

    public Parser() {
    }

    public ArrayList<UserInfo> openFile() {
        FileOperator operator = new FileOperator();
        File file = operator.getFiles();
        ArrayList<UserInfo> beanList = new ArrayList<UserInfo>();
        String str;
        try {
            str = operator.readFile(file);
            while (str.contains("END:VCARD")) {
                String beans = new String();
                beans = str.substring(str.indexOf("BEGIN:VCARD"), str.indexOf("END:VCARD") + 9);
                beans = beans + "\n";
                UserInfo userBean = Converter.createBeans(beans);
                beanList.add(userBean);
                beans = beans.substring(0, beans.lastIndexOf("\n"));
                str = str.replace(beans, "").trim();
            }
            Collections.sort(beanList);
            //遍历并确定分组
            AllUtil.group = new ArrayList<Groups>();
            for (int i = 0; i < beanList.size(); i++) {
                boolean found = false;
                String gn = beanList.get(i).getCATEGORIES();
//                System.out.println(i+"=gn="+gn);
                for (int j = 0; j < AllUtil.group.size(); j++) {
                    if (gn.equals(AllUtil.group.get(j).getGroupName())) {
                        AllUtil.group.get(j).setCount(AllUtil.group.get(j).getCount() + 1);
                        found = true;
                        break;
                    }
                }
                if (found == false) {
                    AllUtil.group.add(new Groups(gn, 1));
                }
            }
//            for (int i = 0; i < AllUtil.group.size(); i++) {
//                System.out.println(i+"="+AllUtil.group.get(i).getGroupName());
//            }
//             AllUtil.group.add(new Groups("test", 1));
            Collections.sort(AllUtil.group);
        } catch (IOException ex) {
            System.out.println("在打开文件时出现异常,openFile方法的时候");
            Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
        }
        return beanList;
    }

    public void saveFile(ArrayList<UserInfo> beansList) {
        FileOperator operator = new FileOperator();
        File file = operator.saveFile();
        try {
            Converter.writeFile(file, beansList);
        } catch (Exception ex) {
            System.out.println("在保存文件时出现错误,savefile方法的时候");
            Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
